package goulu.bloggy.com.Connections;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import goulu.bloggy.com.Helpers.PostHelper;
import goulu.bloggy.com.Models.User;

public class AccountMysqlConnection implements Runnable
{
	private Handler responseHandler;
	public static final int ADD_ACCOUNT = 1;
	public static final int GET_ACCOUNT = 2;
	public static final int ERROR = 0;
	
	private String handledUsername;
	private String handledPassword;
	private int connectionMethod;
	
	public AccountMysqlConnection(Handler response, int connectionMethod, String username, String password)
	{
		this.handledUsername = username;
		this.handledPassword = password;
		this.responseHandler = response;
		this.connectionMethod = connectionMethod;
	}
	
	public AccountMysqlConnection(Handler response, int connectionMethod, String username)
	{
		this.responseHandler = response;
		this.handledUsername = username;
		this.connectionMethod = connectionMethod;
	}
	
	public void insertAccount(String username, String password)
	{
		GregorianCalendar cal = (GregorianCalendar)Calendar.getInstance();
		String currentDate = PostHelper.gregorianCalendarToString(cal);
		
		ArrayList<NameValuePair> accountEntity = new ArrayList<NameValuePair>();
		accountEntity.add(new BasicNameValuePair("username", username));
		accountEntity.add(new BasicNameValuePair("password", password));
		accountEntity.add(new BasicNameValuePair("creationdate", currentDate));
		try
		{
			HttpClient client = new DefaultHttpClient();
			HttpPost post = new HttpPost("http://users.metropolia.fi/~peteraa/android/bloggy/addAccount.php");
			post.setEntity(new UrlEncodedFormEntity(accountEntity));
			client.execute(post);
			Message msg = responseHandler.obtainMessage();
			msg.what = ADD_ACCOUNT;
			msg.obj = "Account created!";
			responseHandler.sendMessage(msg);
		}
		catch(Exception e)
		{
			Log.e("AccountMysqlConnection.insertAccount()", "httppost failed", e);
		}
	}

	public void getUserAccount(String username) 
	{
		ArrayList<NameValuePair> accountEntity = new ArrayList<NameValuePair>();
		accountEntity.add(new BasicNameValuePair("username", username));
		try 
		{
			HttpClient client = new DefaultHttpClient();
			HttpPost post = new HttpPost("http://users.metropolia.fi/~peteraa/android/bloggy/getAccount.php");
			post.setEntity(new UrlEncodedFormEntity(accountEntity));
			HttpResponse response = client.execute(post);
			HttpEntity entity = response.getEntity();
			String result = EntityUtils.toString(entity);

			Log.d("query result: ", result);
			try
			{
				JSONArray jsonArray = new JSONArray(result);
				User user = new User();

				JSONObject jObject = jsonArray.getJSONObject(0);
				user.setUsername(jObject.getString("username"));
				user.setPassword(jObject.getString("password"));
				user.setId(jObject.getInt("id"));
					
				Message msg = responseHandler.obtainMessage();
				msg.obj =  user;
				msg.what = GET_ACCOUNT;
				responseHandler.sendMessage(msg);
			}
			catch(Exception e)
			{
				Message msg = responseHandler.obtainMessage();
				if(result.equals("null"))
				{
					msg.obj = "Wrong Login information!";
				}
				else
				{
					msg.obj = "Could not connect to Database or empty result!";
				}
				msg.what = ERROR;
				responseHandler.sendMessage(msg);
			}
		}
		catch(Exception e)
		{
			Log.e("PresidentConnection.getAllPresidents()", "Url fail", e);
		}
	}

	@Override
	public void run() 
	{
		if(connectionMethod == ADD_ACCOUNT)
		{
			this.insertAccount(handledUsername, handledPassword);
		}
		else if(connectionMethod == GET_ACCOUNT)
		{
			this.getUserAccount(handledUsername);
		}
	}
}
